package com.mtw.bbs.message.service.impl;



import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mtw.bbs.common.core.vo.Result;
import com.mtw.bbs.message.mapper.MessageExtendMapper;
import com.mtw.bbs.message.pojo.entity.MessageExtend;
import com.mtw.bbs.message.pojo.vo.MessageExtendVo;
import com.mtw.bbs.message.service.MessageExtendService;
import com.mtw.bbs.userAdmin.pojo.dto.UserDto;
import com.mtw.bbs.userAdmin.feign.UserClient;
import com.mtw.bbs.userAdmin.pojo.vo.UserInfoVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 消息扩展内容逻辑层
 */
@Slf4j
@RequiredArgsConstructor
@Service("messageExtendService")
public  class MessageExtendServiceImpl extends ServiceImpl<MessageExtendMapper, MessageExtend> implements MessageExtendService {


    private final UserClient userClient;





    /**
     * 分页获取消息扩展内容
     *
     * @param page         当前页
     * @param size         分页大小
     * @param id           消息id
     * @return             分页结果
     */
    @Override
    public Page<MessageExtendVo> getMessagExtendVoPage(int page, int size, String id) {

        LambdaQueryWrapper<MessageExtend> qw = new LambdaQueryWrapper<>();
        qw.select(MessageExtend::getCreatedBy);
        qw.eq(MessageExtend::getMsgId,id);
        qw.orderByAsc(MessageExtend::getCreatedDate);

        Page<MessageExtend> entityPage = page(new Page<>(page, size), qw);

        Page<MessageExtendVo> voPge = new Page<>(page,size,0);
        if (entityPage.getRecords().isEmpty()){
            return voPge;
        }
        voPge.setTotal(entityPage.getTotal());

       Map<String, UserInfoVo> userMap = new HashMap<>(size);
//        Result<List<UserDto>> listResult = userClient.userinfoByIds(entityPage.getRecords().stream().map(MessageExtend::getCreatedBy).toList().toArray(String[]::new));
//        if (listResult.isSuccess() && listResult.getData() != null){
//            for (UserDto x : listResult.getData()) {
//                userMap.put(x.getId(),x.toVO());
//            }
//        }
        List<MessageExtendVo> list = entityPage.getRecords().stream().map(x -> {
            MessageExtendVo vo = new MessageExtendVo();
            vo.setSenderInfo(userMap.get(x.getCreatedBy()));
            return vo;
        }).collect(Collectors.toList());
        voPge.setRecords(list);

        return voPge;
    }



}
